<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<style>
  #btn_download {
    -webkit-appearance: none;
  }
  #detailModalWrapper .fixed-table-pagination {
    display: none !important;
  }

  @media (min-width: 992px) {
    .modal-lg {
      width: 1200px;
    }
  }
  @media (min-width: 992px) {
    .modal-lg, .modal-xl {
      max-width: 1200px
    }
  }
</style>
<div class="content-header">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h1 class="m-0 text-dark">网关管理</h1>
      </div><!-- /.col -->
      <div class="col-sm-6">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a th:href="@{../admin}">首页</a></li>
          <li class="breadcrumb-item active">配置中心</li>
          <li class="breadcrumb-item active">网关管理</li>
        </ol>
      </div><!-- /.col -->
    </div><!-- /.row -->
  </div><!-- /.container-fluid -->
</div>
<!-- Main content -->
<section class="content">
  <div class="card card-info">
    <form id="searchForm" class="needs-validation form-inline" novalidate="">
      <div class="form-group">
        <label for="gatewayIp">网关ip:</label>
        <input type="text" class="form-control m-2" id="gatewayIp">
      </div>
      <div class="form-group">
        <label for="gatewayName">网关名称:</label>
        <input type="text" class="form-control m-2" id="gatewayName">
      </div>
      <div class="form-group">
        <button class="btn btn-primary ml-3" type="submit">查询</button>
        <button class="btn btn-default ml-2" type="reset">重置</button>
      </div>
    </form>
  </div>
  <div class="card card-body">
    <div id="toolbar" class="btn-group">
      <button id="btn_sync" type="button" class="btn btn-primary">
        <span class="glyphicon glyphicon-upload" aria-hidden="true"></span>同步数据
      </button>
      <button id="btn_version" type="button" class="btn btn-info">
        <span class="glyphicon glyphicon-upload" aria-hidden="true"></span>版本查询
      </button>
    </div>
    <table class="table-sm" id="table"></table>
  </div>
</section>

<!-- 详情模态框 -->
<section id="detailModalWrapper">
  <div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">详情</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div id="detailFormContent">
            <table class="table-sm" id="tableInner"></table>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal">确定</button>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- 指令模态框 -->
<section id="generateModalWrapper">
  <div class="modal fade" id="generateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-dialog-centered" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">下发命令</h5>
          <button type="button" class="close" data-dismiss="modal">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <textarea id="generateCommand" style="width: 100%; height: 200px"></textarea>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
          <button type="button" class="btn btn-secondary" id="seeOrder">查看结果</button>
          <button type="button" class="btn btn-primary" id="assignOrder">下发命令</button>
        </div>
      </div>
    </div>
  </div>
</section>

<script>

  $(function () {
    window.operateEvents = {
      // 点击显示指标
      'click .btn_show': function (e, value, row, index) {
        showDetail(row)
      },
      // 点击生成指令
      'click .btn_generate': function (e, value, row, index) {
        generateRow(row.id, row.command)
      }
    }
    var columns = [
      {checkbox: true},
      {
        field: 'gatewayType',
        title: '网关类型',
        align: "center",
        formatter: function(value, row, index) {
          if (row.gatewayType === 1) {
            return "连线网关";
          } else {
            return "4G网关"
          }
        }
      }, {
        field: 'gatewayIp',
        title: '网关ip',
        align: "center"
      }, {
        field: 'gatewayName',
        title: '网关名称',
        align: "center"
      }, {
        field: 'count',
        title: '指标数量',
        align: "center",
      }, {
        field: 'status',
        title: '状态',
        align: "center",
        formatter: function(value, row, index) {
          if (row.status) {
            return "在线";
          } else {
            return "<span style='color: #DC3545'>离线</span>"
          }
        }
      }, {
        field: 'onlineTime',
        title: '在线时间',
        align: "center"
      }, {
        field: 'version',
        title: '版本号',
        align: "center"
      }, {
        field: 'operation',
        title: '操作',
        align: "center",
        width: '300',
        events: operateEvents,
        formatter: operationFormatter
      }];

    function operationFormatter(value, row, index) {
      var show = '<button class="btn btn-info btn-sm ml-1 btn_show">详情</button>';
      var generate = row.needSend ? '<button class="btn btn-danger btn-sm ml-1 btn_generate">下发命令</button>' : '';
      return show + generate;
    }

    var options = {
      id: "#table",
      url: '/cfg/gateway',
      columns: columns,
      toolbar: '#toolbar',
      showRefresh: true,
      queryParams: queryParams
    }
    Core.initTable(options);

    function refreshTable() {
      Core.refreshTable("#table")
    }

    // 查询参数
    function queryParams(params) {
      return {
        page: params.pageNumber,
        size: params.pageSize,
        gatewayIp: $("#gatewayIp").val(),
        gatewayName: $("#gatewayName").val(),
      };
    }

    // 查询
    $('#searchForm').submit(function (event) {
      event.preventDefault();
      event.stopPropagation();
      refreshTable();
    })

    // 同步数据
    $('#btn_sync').on('click', function() {
      Core.confirm("确定要同步数据吗？", function () {
        Core.getAjax("/cfg/interaction", null, function(res) {
          if (res.code === 1) {
            window.location.reload();
          } else {
            layer.msg(res.message);
          }
        }, 2)
      })
    })

    // 查询版本号
    $('#btn_version').on('click', function() {
      Core.confirm("确定要查询版本号吗？", function () {
        Core.getAjax("/cfg/gateway/version", null, function(res) {
          if (res.code === 1) {
            layer.msg("查询成功，如果没有获取到，请刷新并检查网关是否在线");
            setTimeout(() => {
              window.location.reload();
            }, 2000)
          } else {
            layer.msg(res.message);
          }
        }, 2)
      })
    })

    /**
     * 显示详情
     */
    function showDetail(row) {
      $("#detailModal").modal('show');
      $('#tableInner').bootstrapTable('load', row.indicators);
    }

    let commandForGenerate;
    /**
     * 生成下发指令
     * @param id 网关id
     * @package command 网关连接命令
     */
    function generateRow(id, command) {
      Core.postAjax("/cfg/gateway/generate", {message: command}, function (data) {
        if (data.code === 1) {
          $("#generateModal").modal('show');
          $("#generateCommand").val(data.data.command);
          commandForGenerate = command;
        } else {
          layer.msg(data.message);
        }
      }, 2)
    }

    /**
     * 下发指令
     */
    $('#assignOrder').on('click', function() {
      Core.confirm("确定要下发命令？", function() {
        let command = $("#generateCommand").val();
        let message = commandForGenerate;
        var data = {
          command, message
        }
        Core.postAjax("/cfg/gateway/writeCollectCommand", data, function(res) {
          if (res.code === 1) {
            layer.msg("指令已发出，请稍后查询结果");
          } else {
            layer.msg(res.message);
          }
        })
      }, 1)
    })

    /**
     * 查看下发结果
     */
    $('#seeOrder').on('click', function() {
      Core.postAjax("/cfg/gateway/getCollectResult", {message: commandForGenerate}, function(res) {
        if (res.code === 1) {
          layer.msg("指令下发成功");
        } else {
          layer.msg(res.message);
        }
      }, 1)
    })

    /**
     * 重新刷新
     */
    $('#btn_refresh').on('click', function () {
      Core.confirm("是否要刷新数据？", function () {
        Core.getAjax("/cfg/gateway/refresh", null, function(res) {
          if (res.code === 1) {
            layer.msg(res.message);
            window.location.reload();
          } else {
            layer.msg(res.message);
          }
        }, 2)
      })
    });


    var innerColumns = [
      {
        title: '序号',
        field: '',
        align: 'center',
        formatter: function (value, row, index) {
          var pageSize = $('#tableInner').bootstrapTable('getOptions').pageSize;     //通过table的#id 得到每页多少条
          var pageNumber = $('#tableInner').bootstrapTable('getOptions').pageNumber; //通过table的#id 得到当前第几页
          return pageSize * (pageNumber - 1) + index + 1;    // 返回每条的序号： 每页条数 *（当前页 - 1 ）+ 序号
        }
      },
      {
        field: 'serialNumber',
        title: '串口号',
        align: "center"
      },
      {
        field: 'id',
        title: '指标id',
        align: "center"
      }, {
        field: 'indicatorName',
        title: '指标名称',
        align: "center"
      }, {
        field: 'deviceName',
        title: '设备名称',
        align: "center",
      }, {
        field: 'installPos',
        title: '安装地点',
        align: "center"
      }, {
        field: 'command',
        title: '采集命令',
        align: "center"
      }, {
        field: 'frequency',
        title: '采集频率',
        align: "center"
      }, {
        field: 'startBit',
        title: '开始位',
        align: "center"
      }, {
        field: 'takeBit',
        title: '取位',
        align: "center"
      }, {
        field: 'authCode',
        title: '校验协议',
        align: "center"
      }];

    var innerOptions = {
      id: "#tableInner",
      columns: innerColumns
    }
    Core.initTable(innerOptions);

  });
</script>